const Controller = require('egg').Controller;

class WXAuthController extends Controller {

    async getcookies () {

       const { ctx, app } = this;

       const company_code = ctx.query.company_code;

       const sessionid = ctx.cookies.get('juyou-ticket-' + company_code);

       //console.log(sessionid);

       ctx.helper.success(sessionid);
    }


    async clearinfo () {

        const { ctx, app } = this;

        const company_code = ctx.query.company_code;

        const sessionid = ctx.cookies.get('juyou-ticket-' + company_code);

        console.log(sessionid);

        if(sessionid == undefined){
            ctx.helper.success('无需清除');
        }else{
            const res = await app.redis.get('member').del('juyou_ticket_' + sessionid);
            ctx.cookies.set('juyou-ticket-' + company_code, null, {
                'domain' : '.hidlq.com'
            });

            ctx.cookies.set('juyou-ticket-' + company_code, null, {
                'domain' : 'shop.hidlq.com'
            });

            ctx.cookies.set('juyou-ticket-' + company_code, null, {
                'domain' : 'api.hidlq.com'
            });

            ctx.helper.success('清除完成');
        }
    }






    async getUserInfo() {

        const { ctx, app } = this;

        const sessionid = ctx.query.sessionid;

        const sessionV = await app.redis.get('member').hget('juyou_ticket_' + sessionid, 'id');

        ctx.helper.success(sessionV);


    }


    async getWXAuthPath () {

        const { ctx, app } = this;
        const { logger } = ctx;

        const company_code = ctx.query.company_code;
        const rurl = ctx.query.rurl;

        logger.info(company_code);
        logger.info(rurl);

        const companyInfo = await ctx.service.company.info(company_code);

        const successurl = 'https://api.hidlq.com/v1/un/getwxcode';

        let url = 'https://open.weixin.qq.com/connect/oauth2/authorize?';

        url += 'appid=' + companyInfo.appid;

        url += '&redirect_uri=' + encodeURIComponent(successurl);

        url += '&response_type=code&scope=snsapi_userinfo';

        const uuid = await ctx.service.util.uuid(40, 16);
        //const msg = company_code + '@dlq@' + companyInfo.appid + '@dlq@' + companyInfo.appsecret + '@dlq@' + companyInfo.wxid + '@dlq@' + companyInfo.pay_wxid + '@dlq@' + rurl;
        const msg = company_code + '@dlq@' + rurl;

        //await app.redis.get('tmp').hset('dlq_tmp', uuid, msg);
        await app.redis.get('tmp').set(uuid, msg);
        await app.redis.get('tmp').expire(uuid, 60 * 60 * 24);

        url += '&state=' + uuid + '#wechat_redirect';

        ctx.helper.success(url);
    }



    async getWXAuthCode () {

        const { ctx, app } = this;
        const { logger } = ctx;

        const code = ctx.query.code;
        const state = ctx.query.state;



    }


    //0,不需要授权， 1，需要授权
    async checkNeedAuth () {

        const { ctx, app } = this;
        const { logger } = ctx;

        const company_code = ctx.query.company_code;

        logger.info(company_code);

        //
        if(company_code == undefined){
            ctx.helper.success('2');
            return;
        }

        //判断是否已经登录
        const sessionid = ctx.cookies.get('juyou-ticket-' + company_code);

        console.log(sessionid);

        logger.info('juyou_ticket_' + sessionid);

        let cc = await ctx.service.util.uuid(20, 16);

        let dd = ctx.helper.dateFtt('YYYY-MM-dd_hh:mm:ss', new Date());
        //记日志
        await app.redis.get('test').set(cc + '_' + dd + '_checkNeedAuth' , '得到的11sessionid : ' + sessionid);

        let sessionV = '';

        //如果redis里有信息，说明已经登录成功，不需要授权。
        if(sessionid !== undefined){
            sessionV = await app.redis.get('member').hget('juyou_ticket_' + sessionid, 'id');
            if (sessionV !== null) {
                //不需要授权
                ctx.helper.success('66');
                return;
            }
        }

        cc = await ctx.service.util.uuid(20, 16);

        dd = ctx.helper.dateFtt('YYYY-MM-dd_hh:mm:ss', new Date());
        //记日志
        await app.redis.get('test').set(cc + '_' + dd + '_checkNeedAuth' , '需要授权');

        //ctx.cookies.set('juyou-ticket', '1212121211212211');
        
        //需要授权
        ctx.helper.success('154');

    }


    async auth1 () {
        console.log('auth');

        const { ctx, app } = this;
        const { logger } = ctx;

        //1.根据company_code获得 wxid,appid
        const company_code = ctx.query.company_code;
        const rurl = ctx.query.rurl;

        logger.info(company_code);
        logger.info(rurl);

        if(company_code === undefined){
            ctx.helper.error(103, '需要company_code参数');
            return;
        }

        if(rurl === undefined){
            ctx.helper.error(1031, '需要rurl参数');
            return;
        }

        const companyInfo = await ctx.service.company.info(company_code);

        logger.info(companyInfo);

        if(companyInfo == undefined){
            ctx.helper.error(102, '该机构没有配置服务号');
            return;
        }


        let cooiesuuid = ctx.cookies.get('juyou-ticket-' + company_code);



        let cc = await ctx.service.util.uuid(20, 16);

        let dd = ctx.helper.dateFtt('YYYY-MM-dd_hh:mm:ss', new Date());
        //记日志
        await app.redis.get('test').set(cc + '_' + dd + '_auth1' , '获得的cooiesuuid : ' + cooiesuuid);


        if(cooiesuuid == undefined){
            //5.存cookie
            //登录成功后续操作
            cooiesuuid = await ctx.service.util.uuid(40, 16);
            // 客户端的cookie
            ctx.cookies.set('juyou-ticket-' + company_code, cooiesuuid, {
                'domain' : '.hidlq.com',
                'maxAge' : 1000 * 60 * 60 * 24 * 14,
            });
        }

        cc = await ctx.service.util.uuid(20, 16);

        dd = ctx.helper.dateFtt('YYYY-MM-dd_hh:mm:ss', new Date());
        //记日志
        await app.redis.get('test').set(cc + '_' + dd + '_auth1' , '处理完之后的cooiesuuid : ' + cooiesuuid);



        const successurl = 'https://api.hidlq.com/v1/un/getwxcodetest';

        let url = 'https://open.weixin.qq.com/connect/oauth2/authorize?';

        url += 'appid=' + companyInfo.appid;

        url += '&redirect_uri=' + encodeURIComponent(successurl);

        url += '&response_type=code&scope=snsapi_userinfo';

        const uuid = await ctx.service.util.uuid(40, 16);
        //const msg = company_code + '@dlq@' + companyInfo.appid + '@dlq@' + companyInfo.appsecret + '@dlq@' + companyInfo.wxid + '@dlq@' + companyInfo.pay_wxid + '@dlq@' + rurl;
        const msg = company_code + '@dlq@' + rurl + '@dlq@' + cooiesuuid;

        //await app.redis.get('tmp').hset('dlq_tmp', uuid, msg);
        await app.redis.get('tmp').set(uuid, msg);
        await app.redis.get('tmp').expire(uuid, 60 * 60 * 24);

        url += '&state=' + uuid + '#wechat_redirect';


        cc = await ctx.service.util.uuid(20, 16);

        dd = ctx.helper.dateFtt('YYYY-MM-dd_hh:mm:ss', new Date());
        //记日志
        await app.redis.get('test').set(cc + '_' + dd + '_auth1' , '跳微信的url : ' + url);


        logger.info(url);

        //ctx.helper.success(url);

        ctx.redirect(url);

        //const result = await ctx.curl(url);

        //logger.info(result);
    }


    //由微信授权后跳转，带回code和state中的内容。
    async getwxcode () {

        console.log('getwxcode');

        const { ctx, app } = this;
        const { logger } = ctx;

        const code = ctx.query.code;
        const state = ctx.query.state;

        console.log(state);

        if(state == undefined){
            ctx.helper.error(103, '缺少 state 参数');
            return;
        }

        //const msg = await app.redis.get('tmp').hget('dlq_tmp', state);
        const msg = await app.redis.get('tmp').get(state);
        //app.redis.get('tmp').del('dlq_tmp', state);

        const arr = msg.split('@dlq@');

        if(arr.length !== 3){
            ctx.helper.error(104, 'state 不正确');
            return;
        }

        const company_code = arr[0];
        const rurl = arr[1];
        const uuid = arr[2];

        const companyInfo = await ctx.service.company.info(company_code);
        logger.info(companyInfo);

        const appid = companyInfo.appid;
        const secret = companyInfo.appsecret;
        const wxid = companyInfo.wxid;
        const pay_wxid = companyInfo.pay_wxid;
        const cash_wxid = companyInfo.cash_wxid;
        

        logger.info('company_code : ' + company_code);
        logger.info('appid : ' + appid);
        logger.info('secret : ' + secret);
        logger.info('wxid : ' + wxid);
        logger.info('pay_wxid : ' + pay_wxid);
        logger.info('cash_wxid : ' + cash_wxid);
        logger.info('rurl : ' + rurl);

        let url = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
        url += 'appid=' + appid;
        url += '&secret=' + secret;
        url += '&code=' + code;
        url += '&grant_type=authorization_code';

        const result = await ctx.curl(url, { dataType: 'json' });

        console.log(result);
        logger.info('accesstoken :');
        logger.info(result);

        if(result.data.errcode !== undefined){
            ctx.helper.error(106, result.data.errmsg);
            return;
        }

        let url1 = 'https://api.weixin.qq.com/sns/userinfo?';
        url1 += 'access_token=' + result.data.access_token;
        url1 += '&openid=' + result.data.openid + '&lang=zh_CN';

        const result1 = await ctx.curl(url1, { dataType: 'json' });

        console.log(result1);
        logger.info('用户信息 : ');
        logger.info(result1);

        if(result1.data.errcode !== undefined){
            ctx.helper.error(106, result1.data.errmsg);
            return;
        }

        //4.获取用户openid
        const userinfo = {
            'nickname' : result1.data.nickname,
            'headimgurl' : result1.data.headimgurl,
            'openid' : result1.data.openid,
        };
        
        const user_base = 'wx' + wxid + '-' + userinfo.openid;
        logger.info('用户user_base : ' + user_base);

        
        //7.查询用户，看是否存在，
        const memberinfo = await ctx.service.member.info(user_base, company_code);
        console.log('memberinfo');
        console.log(memberinfo);
        logger.info('memberinfo');
        logger.info(memberinfo);


        //8.已经存在，更新；不存在插入。
        if(memberinfo !== undefined){
            logger.info('已经存在');

            const r = await ctx.service.member.update({
                nickname : userinfo.nickname, 
                headimgurl : userinfo.headimgurl, 
                user_base,
                company_code,
            });

            if(!r){
                logger.info('更新用户信息失败');
                ctx.helper.error(105, '更新用户信息失败');
                return;
            }

        }else{
            const r = await ctx.service.member.create({
                openid : userinfo.openid, 
                nickname : userinfo.nickname, 
                headimgurl : userinfo.headimgurl, 
                user_base, 
                wxid, 
                company_code,
            })

            if(!r){
                logger.info('添加用户失败');
                ctx.helper.error(105, '添加用户失败');
                return;
            }
        }

        

        //6.存redis
        const info = {
            'id' : user_base,
            'bind_seller_company_code' : company_code,
            'nickname' : userinfo.nickname,
            'headimgurl' : userinfo.headimgurl,
            cash_wxid,
        };

        logger.info('juyou_ticket_' + uuid + '写redis开始。');


        let cc = await ctx.service.util.uuid(20, 16);

        let dd = ctx.helper.dateFtt('YYYY-MM-dd_hh:mm:ss', new Date());
        //记日志
        await app.redis.get('test').set(cc + '_' + dd + '_getwxcode' , '准备写redis的uuid : ' + uuid);



        for (let key in info) {
            console.log(key);
            await app.redis.get('member').hset('juyou_ticket_' + uuid, key, info[key]);
        }
        await app.redis.get('member').expire('juyou_ticket_' + uuid, 60 * 60 * 24 * 15);
        
        logger.info('juyou_ticket_' + uuid + '写redis结束。');


        const dlqid =  await app.redis.get('member').hget('juyou_ticket_' + uuid, 'id');

        logger.info('juyou_ticket_' + uuid + ' 的 dlqid : ' + dlqid);


        cc = await ctx.service.util.uuid(20, 16);

        dd = ctx.helper.dateFtt('YYYY-MM-dd_hh:mm:ss', new Date());
        //记日志
        await app.redis.get('test').set(cc + '_' + dd + '_getwxcode' , '写完redis 读id : ' + dlqid);



        console.log('juyou_ticket_' + uuid);
        logger.info('juyou_ticket_' + uuid);


        logger.info('即将跳转 : ' + rurl + '&v=' + (new Date().getTime()));
        ctx.redirect(rurl);
        logger.info('跳转结束 : ' + rurl + '&v=' + (new Date().getTime()));

        // 设置响应体和状态码
        //ctx.helper.success(rurl);

    }



    // async checkNeedAuth () {

    //     const { ctx, app } = this;
    //     const { logger } = ctx;

    //     const company_code = ctx.query.company_code;

    //     //
    //     if(company_code == undefined){
    //         ctx.helper.success('2');
    //         return;
    //     }

    //     //判断是否已经登录
    //     const sessionid = ctx.cookies.get('juyou-ticket-' + company_code);

    //     console.log(sessionid);

    //     logger.info('juyou_ticket_' + sessionid);

    //     let sessionV = '';

    //     //如果redis里有信息，说明已经登录成功，不需要授权。
    //     if(sessionid !== undefined){
    //         sessionV = await app.redis.get('member').hget('juyou_ticket_' + sessionid, 'id');
    //         if (sessionV !== null) {
    //             //不需要授权
    //             ctx.helper.success('0');
    //             return;
    //         }
    //     }


    //     //ctx.cookies.set('juyou-ticket', '1212121211212211');
        
    //     //需要授权
    //     ctx.helper.success({
    //         company_code,
    //         sessionid,
    //         sessionV,
    //     });

    // }

}
module.exports = WXAuthController;